﻿using UnityEngine;
using System;
using System.Collections;

namespace Hont.UMotionGraph
{
    public class MGFractalNoiseEffector : MoGraphEffector
    {
        public Texture2D fractalNoise;
        public float noiseScale = 1;
        public float force = 1;
        public float timeScale = 1;
        float mTime;


        public override void Init(IMoGraphContainer container)
        {
            base.Init(container);

        }

        public override Vector3 Execute(int inx, Vector3 inValue, float fallOffProportion)
        {
            mTime += timeScale * Time.deltaTime;
            var t = mTime;

            var addX = GetNoise((inValue.x + t) * noiseScale, 0);
            var addY = GetNoise((inValue.x + t) * noiseScale, (inValue.y + t) * noiseScale);
            var addZ = GetNoise((inValue.x + inValue.z + t) * noiseScale, (inValue.y + inValue.z + t) * noiseScale);

            return inValue + new Vector3(addX, addY, addZ) * force;
        }

        float GetNoise(float x, float y)
        {
            var xRate = 1 - (Mathf.Floor(x + 1) - x);
            var yRate = 1 - (Mathf.Floor(y + 1) - y);

            var sampleX = (int)Mathf.Clamp(fractalNoise.width * xRate, 0, fractalNoise.width);
            var sampleY = (int)Mathf.Clamp(fractalNoise.height * yRate, 0, fractalNoise.height);

            var color = fractalNoise.GetPixel(sampleX, sampleY);

            return color.r;
        }
    }
}
